package com.jsb.laundry.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsb.laundry.common.constant.CommonConstants;
import com.jsb.laundry.common.exception.BusinessException;
import com.jsb.laundry.common.exception.ErrorCode;
import com.jsb.laundry.dao.JsbPostUserFollowersMapper;
import com.jsb.laundry.dao.JsbPostsMapper;
import com.jsb.laundry.model.dto.posts.PostUserFansQueryRequest;
import com.jsb.laundry.model.dto.posts.PostUserFollowQueryRequest;
import com.jsb.laundry.model.dto.posts.PostUserFollowersQueryRequest;
import com.jsb.laundry.model.entity.*;
import com.jsb.laundry.model.vo.PostsUserFollowersVO;
import com.jsb.laundry.model.vo.PostsVO;
import com.jsb.laundry.model.vo.UserVO;
import com.jsb.laundry.service.JsbPostLikesService;
import com.jsb.laundry.service.JsbPostUserFollowersService;
import com.jsb.laundry.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author ching
* @description 针对表【jsb_post_user_followers(帖子用户关注关系的表)】的数据库操作Service实现
* @createDate 2023-08-15 11:52:11
*/
@Service
public class JsbPostUserFollowersServiceImpl extends ServiceImpl<JsbPostUserFollowersMapper, JsbPostUserFollowers>
    implements JsbPostUserFollowersService{

    @Resource
    private JsbPostsMapper postsMapper;

    @Resource
    private JsbPostUserFollowersMapper postUserFollowersMapper;

    /**
     * 关注 / 取消关注
     *
     * @param userId
     * @param followerId
     * @return
     */
    @Override
    public int doPostUserFollow(String userId, String followerId) {
        //TODO 判断用户是否存在

        // 是否已点赞
        // 锁必须要包裹住事务方法
        JsbPostUserFollowersService postFollowService = (JsbPostUserFollowersService) AopContext.currentProxy();
        synchronized (userId.intern()) {
            return postFollowService.doPostUserFollowInner(userId, followerId);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int doPostUserFollowInner(String userId, String followerId) {
        JsbPostUserFollowers postuserFollow = new JsbPostUserFollowers();
        postuserFollow.setUserId(userId);
        postuserFollow.setFollowerId(followerId);
        QueryWrapper<JsbPostUserFollowers> postUserFollowQueryWrapper = new QueryWrapper<>(postuserFollow);
        JsbPostUserFollowers oldPostUserFollowThumb = this.getOne(postUserFollowQueryWrapper);
        boolean result;
        // 已关注
        if (oldPostUserFollowThumb != null) {
            result = this.remove(postUserFollowQueryWrapper);
            if (result) {
                //TODO 关注数 - 1

            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        } else {
            // 未关注
            result = this.save(postuserFollow);
            if (result) {
                //TODO 关注数 + 1

            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
        return 0;
    }

    @Override
    public Page<PostsUserFollowersVO> listUserFollowVOPage(String loginUserId, Page<UserDetail> postUserFollowersPage, HttpServletRequest request) {
        List<UserDetail> postUserFollowersList = postUserFollowersPage.getRecords();
        Page<PostsUserFollowersVO> postsUserFollowersVOPage = new Page<>(postUserFollowersPage.getCurrent(), postUserFollowersPage.getSize(), postUserFollowersPage.getTotal());
        if (CollectionUtils.isEmpty(postUserFollowersList)) {
            return postsUserFollowersVOPage;
        }
        // 填充信息
        List<PostsUserFollowersVO> postsUserFollowersVOList = postUserFollowersList.stream().map(postUserFollowers -> {
            UserVO userVO = new UserVO();
            userVO.setUserId(postUserFollowers.getUserId());
            userVO.setUserName(postUserFollowers.getUserName());
            userVO.setUserAvatar(postUserFollowers.getUserAvatar());
            PostsUserFollowersVO postsUserFollowersVO = new PostsUserFollowersVO();
            postsUserFollowersVO.setUser(userVO);
            QueryWrapper<JsbPostUserFollowers> postUserFollowQueryWrapper = new QueryWrapper<>();
            postUserFollowQueryWrapper.eq("user_id", postUserFollowers.getUserId());
            postUserFollowQueryWrapper.in("follower_id", loginUserId);
            JsbPostUserFollowers userFollowers = postUserFollowersMapper.selectOne(postUserFollowQueryWrapper);
            postsUserFollowersVO.setIsMutualAttention(userFollowers != null);

            return postsUserFollowersVO;
        }).collect(Collectors.toList());
        postsUserFollowersVOPage.setRecords(postsUserFollowersVOList);
        return postsUserFollowersVOPage;
    }

    @Override
    public Page<PostsUserFollowersVO> listUserFansVOPage(String loginUserId, Page<UserDetail> postUserFollowersPage, HttpServletRequest request) {
        List<UserDetail> postUserFollowersList = postUserFollowersPage.getRecords();
        Page<PostsUserFollowersVO> postsUserFollowersVOPage = new Page<>(postUserFollowersPage.getCurrent(), postUserFollowersPage.getSize(), postUserFollowersPage.getTotal());
        if (CollectionUtils.isEmpty(postUserFollowersList)) {
            return postsUserFollowersVOPage;
        }
        // 填充信息
        List<PostsUserFollowersVO> postsUserFollowersVOList = postUserFollowersList.stream().map(postUserFollowers -> {
            UserVO userVO = new UserVO();
            userVO.setUserId(postUserFollowers.getUserId());
            userVO.setUserName(postUserFollowers.getUserName());
            userVO.setUserAvatar(postUserFollowers.getUserAvatar());
            PostsUserFollowersVO postsUserFollowersVO = new PostsUserFollowersVO();
            postsUserFollowersVO.setUser(userVO);
            QueryWrapper<JsbPostUserFollowers> postUserFollowQueryWrapper = new QueryWrapper<>();
            postUserFollowQueryWrapper.eq("user_id", loginUserId);
            postUserFollowQueryWrapper.in("follower_id", postUserFollowers.getUserId());
            JsbPostUserFollowers userFollowers = postUserFollowersMapper.selectOne(postUserFollowQueryWrapper);
            postsUserFollowersVO.setIsMutualAttention(userFollowers != null);

            return postsUserFollowersVO;
        }).collect(Collectors.toList());
        postsUserFollowersVOPage.setRecords(postsUserFollowersVOList);
        return postsUserFollowersVOPage;
    }

    @Override
    public Page<JsbPosts> listFollowPostByPage(IPage<JsbPosts> page, Wrapper<JsbPosts> queryWrapper, String userId) {
        if (StringUtils.isAnyBlank(userId)) {
            return new Page<>();
        }
        return baseMapper.listUserFollowerPostByPage(page, queryWrapper, userId);
    }
}




